package org.jeecgframework.web.util;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;

import org.apache.commons.mail.*;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.web.system.pojo.base.ZyEmailEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
/**
 * 
 * @author  张代浩
 *
 */
public class SendMailUtil
{
	
    private static final ExecutorService es = Executors.newFixedThreadPool(5);


//	private static final String smtphost = "";
//	private static final String from = ""; // NOPMD by dzqThinkpad on 16-4-1 下午4:33
//	private static final String fromName = ""; // NOPMD by dzqThinkpad on 16-4-1 下午4:32
//	private static final String charSet = ""; // NOPMD by dzqThinkpad on 16-4-1 下午4:33
//	private static final String username = ""; // NOPMD by dzqThinkpad on 16-4-1 下午4:33
//	private static final String password = ""; // NOPMD by dzqThinkpad on 16-4-1 下午4:33

//	private static final String smtphost = "192.168.1.70";
	private static final String from = "customerservice@cfg-barco.com"; // NOPMD by dzqThinkpad on 16-4-1 下午4:33
	private static final String fromName = "中影巴可"; // NOPMD by dzqThinkpad on 16-4-1 下午4:32
	private static final String charSet = "utf-8"; // NOPMD by dzqThinkpad on 16-4-1 下午4:33
	private static final String username = "customerservice@cfg-barco.com"; // NOPMD by dzqThinkpad on 16-4-1 下午4:33
	private static final String password = "BJV@cs123"; // NOPMD by dzqThinkpad on 16-4-1 下午4:33

	private static Map<String, String> hostMap = new HashMap<String, String>();

	@Autowired
	private static SystemService systemService;

	static {
		// asdc
		hostMap.put("smtp.asdc", "mail.asdc.com.cn");

		// 126
		hostMap.put("smtp.126", "smtp.126.com");

		// qq
		hostMap.put("smtp.qq", "smtp.qq.com");

		// 163
		hostMap.put("smtp.163", "smtp.163.com");

		// sina
		hostMap.put("smtp.sina", "smtp.sina.com.cn");

		// tom
		hostMap.put("smtp.tom", "smtp.tom.com");

		// 263
		hostMap.put("smtp.263", "smtp.263.net");

		// yahoo
		hostMap.put("smtp.yahoo", "smtp.mail.yahoo.com");

		// hotmail
		hostMap.put("smtp.hotmail", "smtp.live.com");

		// gmail
		hostMap.put("smtp.gmail", "smtp.gmail.com");
		hostMap.put("smtp.port.gmail", "465");

//		//barco
//		hostMap.put("smtp.cfg-barco", "smtp.mxhichina.com");
//		hostMap.put("smtp.port.cfg-barco", "465");

		//barco
		hostMap.put("smtp.cfg-barco", "smtp.partner.outlook.cn");
        hostMap.put("smtp.port.cfg-barco", "25");
	}

	public static String getHost(String email) throws Exception {
		Pattern pattern = Pattern.compile("\\w+@(\\w+\\-*\\w+)(\\.\\w+){1,2}");
		Matcher matcher = pattern.matcher(email);
		String key = "unSupportEmail";
		if (matcher.find()) {
			key = "smtp." + matcher.group(1);
		}
		if (hostMap.containsKey(key)) {
			return hostMap.get(key);
		} else {
			throw new Exception("unSupportEmail"); // NOPMD by dzqThinkpad on 16-4-1 下午4:33
		}
	}

	public static int getSmtpPort(String email) throws Exception {
		Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
		Matcher matcher = pattern.matcher(email);
		String key = "unSupportEmail";
		if (matcher.find()) {
			key = "smtp.port." + matcher.group(1);
		}
		if (hostMap.containsKey(key)) {
			return Integer.parseInt(hostMap.get(key));
		} else {
			return 25;
		}
	}


	/**
	 * @author xiul
	 * Description 根据 ftl 模板发送邮件 
	 * @param emailEntity 
	 * @param templatePath 模板地址
	 * @param map 模板参数
	 * @param systemService 
	 */
	public static void sendFtlMail(final ZyEmailEntity emailEntity, final String templatePath, final Map<String, Object> map,final SystemService systemService){
		es.submit(new Runnable() {
			@Override
			public void run() {
				if(StringUtil.isEmpty(emailEntity.getEmailReceiver())){
					return;
				}
				Template template = null;
				Configuration freeMarkerConfig = null;
				MultiPartEmail email = new MultiPartEmail();
				String htmlText = "";
				try {
					// set mail's common parameter
                    email.setTLS(true);
					email.setHostName(getHost(from));
					email.setAuthentication(username, password);
					email.setFrom(from,fromName);
					for(String to : emailEntity.getEmailReceiver().split(";")){
						email.addTo(to);
					}
					email.setSubject(emailEntity.getEmailSubject());
					if(emailEntity.getCcList() != null && emailEntity.getCcList().size() > 0){
						email.setCc(emailEntity.getCcList());
					}
					// set mail's message
					freeMarkerConfig = new Configuration();
					freeMarkerConfig.setDirectoryForTemplateLoading(new File(getFilePath()));
					// 获取模板
					template = freeMarkerConfig.getTemplate(getFileName(templatePath),
							new Locale("Zh_cn"), "UTF-8");
					// 模板内容转换为string
					htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
					email.setMsg(htmlText);

					// set mail's attachment
					if(null != emailEntity.getEmailAttachment()) {
						// attachment's stream, name, mime and description
						byte[] attachment = emailEntity.getEmailAttachment();
						String attachmentName = emailEntity.getEmailAttachmentName();
						String attachmentMIME = getMIMEType(attachmentName);
						String attachmentDesc = emailEntity.getEmailAttachmentDesc();

						email.attach(new ByteArrayDataSource(attachment, attachmentMIME),
								attachmentName, attachmentDesc);
					} else {
						SimpleEmail emailS = new SimpleEmail();
						emailS.setTLS(true);
						emailS.setHostName(getHost(from));
						emailS.setSmtpPort(getSmtpPort(from));
						emailS.setCharset(charSet);
						emailS.setFrom(from, fromName);
						emailS.setAuthentication(username, password);
						for(String to : emailEntity.getEmailReceiver().split(";")){
							emailS.addTo(to);
						}
						emailS.setSubject(emailEntity.getEmailSubject());
						emailS.setMsg(htmlText);
						emailS.send();//发送邮件
						systemService.addLog("发送邮件,接受方:" + emailEntity.getEmailReceiver() + ",内容:" + htmlText, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
						org.jeecgframework.core.util.LogUtil.info("email send true!");
						return;
					}
					email.send();//发送邮件
					systemService.addLog("发送邮件,接受方:" + emailEntity.getEmailReceiver() + ",内容:" + htmlText, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
					org.jeecgframework.core.util.LogUtil.info("email send true!");
				} catch (Exception e) {
					systemService.addLog("发送邮件失败,接受方:" + emailEntity.getEmailReceiver() + ",内容:" + htmlText, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
					e.printStackTrace();
					org.jeecgframework.core.util.LogUtil.info("email send error!");
				}
			}
		});

	}
	
	/**
	 * @author xiul
	 * 2016-7-5 下午3:44:16
	 * Description 发送HTML 邮件 
	 * @param toMailAddr 接收方
	 * @param subject 主题
	 * @param templatePath 模板名
	 * @param map 模板参数
	 */
	public static void sendHTMLeMail(String toMailAddr, String subject, String templatePath, Map<String, Object> map) {
		HtmlEmail hemail = new HtmlEmail();
		Configuration freeMarkerConfig = null;
		Template template = null;
		String htmlTexts = "";
		try {
			freeMarkerConfig = new Configuration();
			freeMarkerConfig.setDirectoryForTemplateLoading(new File(getFilePath()));
			// 获取模板
			template = freeMarkerConfig.getTemplate(getFileName(templatePath),new Locale("Zh_cn"), "UTF-8");
			// 模板内容转换为string
			String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
			htmlTexts = htmlText;
            hemail.setTLS(true);
			hemail.setHostName(getHost(from));
			hemail.setSmtpPort(getSmtpPort(from));
			hemail.setCharset(charSet);
			hemail.setFrom(from, fromName);
			hemail.setAuthentication(username, password);
			hemail.addTo(toMailAddr);
			hemail.setSubject(subject);
			hemail.setHtmlMsg(htmlText);
			String send = hemail.send();
			System.out.println("发送成功，返回参数为:"+send);
			systemService.addLog("发送邮件,接受方:" + toMailAddr + "标题"+subject+",内容:" + htmlTexts, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
		} catch (Exception e) {
			systemService.addLog("发送邮件失败,接受方:" + toMailAddr + "标题"+subject+",内容:" + htmlTexts, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
			e.printStackTrace();
	    }
	}

	/**
	 * 发送普通邮件
	 * @param toMailAddr  收件人
	 * @param subject  主题
	 * @param msg  内容
	 */
	public static void sendeMail(String toMailAddr, String subject,String msg,SystemService systemService) {
		SimpleEmail email = new SimpleEmail();
		try {
            email.setTLS(true);
			email.setHostName(getHost(from));
			email.setSmtpPort(getSmtpPort(from));
			email.setCharset(charSet);
			email.setFrom(from, fromName);
			email.setAuthentication(username, password);
			email.addTo(toMailAddr);
			email.setSubject(subject);
			email.setMsg(msg);
			String send = email.send();
			System.out.println("发送成功，返回参数为:"+send);
			systemService.addLog("发送邮件,接受方:" + toMailAddr + ",内容:" + msg, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
		} catch (Exception e) {
			System.out.println("发送邮件失败");
			systemService.addLog("发送邮件失败,接受方:" + toMailAddr + "标题"+subject+",内容:" + msg, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
			e.printStackTrace();
		}
	}
	/**
	 * @author xiul
	 * 2016-7-12 下午1:20:07
	 * Description 发送带附件Email 
	 * @param toMailAddr 接收地址
	 * @param subject 主题
	 * @param file 附件
	 */
	public static void sendHTMLeMailWithAttach(String toMailAddr, String subject,File file,String...copyPerson){
		try {
			EmailAttachment attachment = new EmailAttachment();
			attachment.setPath(file.getAbsolutePath());
			attachment.setDisposition(EmailAttachment.ATTACHMENT);
			attachment.setName(MimeUtility.encodeText(file.getName()));
			
			MultiPartEmail email = new MultiPartEmail();
			for (String persons : copyPerson) {
				for (String person : persons.split(",")) {
					email.addCc(person);
				}
			}
			email.setTLS(true);
			email.setHostName(getHost(from));
			email.setAuthentication(username, password);
			
			email.addTo(toMailAddr);
			email.setFrom(from, fromName);
			email.setSubject(subject);
			email.attach(attachment);
			email.setCharset("UTF-8");
			String returnMsg = email.send();
			System.out.println("发送带附件邮件返回消息："+returnMsg);
			systemService.addLog("发送邮件,接受方:" + toMailAddr + ",内容:" + subject, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
		} catch (EmailException e) {
			systemService.addLog("发送邮件失败,接受方:" + toMailAddr + "标题"+subject, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @author xiul
	 * 2017-4-11 下午5:24:56
	 * Description 附件 + FTL模板 + （抄送）
	 * @param toMailAddr 收件人地址
	 * @param subject 主题
	 * @param templatePath 内容模板地址
	 * @param templeteMap 内容模板参数
	 * @param file 附件文件
	 * @param copyPerson 抄送人 （可选）
	 */
	public static void sendEMail(String toMailAddr, String subject,String templatePath, Map<String, Object> templeteMap, List<File> files,SystemService systemService,String...copyPerson){
		try {
			Template template = null;
			Configuration freeMarkerConfig = null;
			MultiPartEmail email = new MultiPartEmail();
			
			// set mail's message
			freeMarkerConfig = new Configuration();
			freeMarkerConfig.setDirectoryForTemplateLoading(new File(getFilePath()));
			// 获取模板
			template = freeMarkerConfig.getTemplate(getFileName(templatePath),
					new Locale("Zh_cn"), "UTF-8");
			// 模板内容转换为string
			String msg = FreeMarkerTemplateUtils.processTemplateIntoString(template, templeteMap);
			email.setMsg(msg);
			for (String persons : copyPerson) {
				for (String person : persons.split(",")) {
					email.addCc(person);
				}
			}
			email.setTLS(true);
			email.setHostName(getHost(from));
			email.setAuthentication(username, password);
			
			email.addTo(toMailAddr);
			email.setFrom(from, fromName);
			email.setSubject(subject);
			if(null != files){
				for (File file : files) {
					EmailAttachment attachment = new EmailAttachment();
					attachment.setPath(file.getAbsolutePath());
					attachment.setDisposition(EmailAttachment.ATTACHMENT);
					attachment.setName(MimeUtility.encodeText(file.getName()));
					email.attach(attachment);
				}
			}
			email.setCharset("UTF-8");
			email.send();
			systemService.addLog("发送邮件,接收方："+toMailAddr+",内容为："+msg, Globals.log_type_SEND_EMAIL, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			systemService.addLog("发送邮件失败！,接收方："+toMailAddr, Globals.log_type_SEND_EMAIL, Globals.Log_Leavel_ERROR);
			e.printStackTrace();
		}
	}
	
	/**
	 * 发送邮件 有抄送人 有模版
	 * @param toPerson 发给谁
	 * @param subject 主题
	 * @param filePath 附件地址
	 * @param fileName 空为文件名称，可修改
	 * @param copyPerson 抄送人 ,分割
	 * @param html 根据模版生成的html （getHtmlText）
	 * @return
	 */
	public static String sendMail(String toPerson,String subject,String filePath,String fileName,String copyPerson,String templatePath,Map<String,Object> param,SystemService systemService){
		String returnMsg = "";
		Configuration freeMarkerConfig = null;
		Template template = null;
		String htmlText = "";
		try {
			MultiPartEmail email = new MultiPartEmail();
			email.setTLS(true);
			email.setHostName(getHost(from));
			email.setAuthentication(username, password);
			if(StringUtil.isNotEmpty(copyPerson)){
				String persons[] = copyPerson.split(",");
				for (String person : persons) {
					email.addCc(person);
				}
			}
			if(StringUtil.isNotEmpty(filePath)){
				File file = new File(filePath);
				EmailAttachment attachment = new EmailAttachment();
				attachment.setPath(file.getAbsolutePath());
				attachment.setDisposition(EmailAttachment.ATTACHMENT);
				attachment.setName(StringUtil.isNotEmpty(fileName)?fileName:file.getName());
				email.attach(attachment);
			}
			email.addTo(toPerson);
			email.setFrom(from, fromName);
			email.setSubject(subject);
			email.setCharset("UTF-8");
			freeMarkerConfig = new Configuration();
			freeMarkerConfig.setDirectoryForTemplateLoading(new File(getFilePath()));
			// 获取模板
			template = freeMarkerConfig.getTemplate(getFileName(templatePath), new Locale("Zh_cn"), "UTF-8");
			// 模板内容转换为string
			htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, param);
			if(StringUtil.isNotEmpty(htmlText)){
				email.setMsg(htmlText);
			}
			returnMsg = email.send();
			System.out.println("发送带附件邮件返回消息："+returnMsg);
			systemService.addLog("发送邮件,接收方："+toPerson+",内容为："+htmlText, Globals.log_type_SEND_EMAIL, Globals.Log_Leavel_INFO);
		}catch (IOException e) {
			e.printStackTrace();
			systemService.addLog("发送邮件异常,读取Email模版失败", Globals.log_type_SEND_EMAIL, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			systemService.addLog("发送邮件异常,接收方："+toPerson+",内容为："+htmlText, Globals.log_type_SEND_EMAIL, Globals.Log_Leavel_INFO);
	    } 
		return returnMsg;
	}
	
	
	/**
	 * @author sy
	 * Description 发送HTML 邮件 
	 * @param toMailAddr 接收方
	 * @param subject 主题
	 * @param templatePath 模板名
	 * @param map 模板参数
	 * 并直接添加日志
	 */
	public static void sendHTMLeMail(final String toMailAddr,final String subject,final String templatePath,final Map<String, Object> map,final SystemService systemService) {
		es.submit(new Runnable() {
			@Override
			public void run() {
				HtmlEmail hemail = new HtmlEmail();
				Configuration freeMarkerConfig = null;
				Template template = null;
				String htmlText = "";
				try {
					freeMarkerConfig = new Configuration();
					freeMarkerConfig.setDirectoryForTemplateLoading(new File(getFilePath()));
					// 获取模板
					template = freeMarkerConfig.getTemplate(getFileName(templatePath), new Locale("Zh_cn"), "UTF-8");
					// 模板内容转换为string
					htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
                    hemail.setTLS(true);
                    hemail.setHostName(getHost(from));
					hemail.setSmtpPort(getSmtpPort(from));
					hemail.setCharset(charSet);
					hemail.setFrom(from, fromName);
					hemail.setAuthentication(username, password);
					hemail.addTo(toMailAddr);
					hemail.setSubject(subject);
					hemail.setHtmlMsg(htmlText);
					hemail.send();
					systemService.addLog("发送邮件,接收方：" + toMailAddr + ",内容为：" + htmlText, Globals.log_type_SEND_EMAIL, Globals.Log_Leavel_INFO);
				} catch (IOException e) {
					e.printStackTrace();
					systemService.addLog("发送邮件异常,读取Email模版失败", Globals.log_type_SEND_EMAIL, Globals.Log_Leavel_INFO);
				} catch (Exception e) {
					e.printStackTrace();
					systemService.addLog("发送邮件异常,接收方：" + toMailAddr + ",内容为：" + htmlText, Globals.log_type_SEND_EMAIL, Globals.Log_Leavel_INFO);
				}
			}
		});
	}

	/**
	 * 获取模板内容
	 * @param templatePath
	 * @param map
	 * @return
	 */
	public static String getHtmlText(String templatePath, Map<String, Object> map){
		  Template template = null;
		  String htmlText = "";
		  try {
			Configuration freeMarkerConfig = null;
			  freeMarkerConfig = new Configuration();
			  freeMarkerConfig.setDirectoryForTemplateLoading(new File(getFilePath()));
			  // 获取模板
			  template = freeMarkerConfig.getTemplate(getFileName(templatePath),new Locale("Zh_cn"), "UTF-8");
				// 模板内容转换为string
			  htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
			  org.jeecgframework.core.util.LogUtil.info(htmlText);
			  systemService.addLog("发送邮件,内容为：" + htmlText, Globals.log_type_SEND_EMAIL, Globals.Log_Leavel_INFO);
		  } catch (Exception e) {
			  systemService.addLog("发送邮件失败,内容为：" + htmlText, Globals.log_type_SEND_EMAIL, Globals.Log_Leavel_INFO);
			  e.printStackTrace();
		}
		  return htmlText;
	}
    
  	public static String getFilePath() {
  		String path = getAppPath(SendMailUtil.class);
  		path = path + File.separator + "jeecg" + File.separator + "template" + File.separator + "zybk" + File.separator;
		path = path.replace("\\", "/");
		org.jeecgframework.core.util.LogUtil.info(path);
		return path;
	}

	private static String getFileName(String path) {
		path = path.replace("\\", "/");
		org.jeecgframework.core.util.LogUtil.info(path);
		return path.substring(path.lastIndexOf("/") + 1);
	}
	
	private static String getMIMEType(String attachmentName) {
		return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
	}
  
	public static String getAppPath(Class cls) {
		// 检查用户传入的参数是否为空
		if (cls == null)
			throw new java.lang.IllegalArgumentException("参数不能为空！");
		ClassLoader loader = cls.getClassLoader();
		// 获得类的全名，包括包名
		String clsName = cls.getName() + ".class";
		// 获得传入参数所在的包
		Package pack = cls.getPackage();
		String path = "";
		// 如果不是匿名包，将包名转化为路径
		if (pack != null) {
			String packName = pack.getName();
			// 此处简单判定是否是Java基础类库，防止用户传入JDK内置的类库
			if (packName.startsWith("java.") || packName.startsWith("javax."))
				throw new java.lang.IllegalArgumentException("不要传送系统类！");
			// 在类的名称中，去掉包名的部分，获得类的文件名
			clsName = clsName.substring(packName.length() + 1);
			// 判定包名是否是简单包名，如果是，则直接将包名转换为路径，
			if (packName.indexOf(".") < 0)
				path = packName + "/";
			else {// 否则按照包名的组成部分，将包名转换为路径
				int start = 0, end = 0;
				end = packName.indexOf(".");
				while (end != -1) {
					path = path + packName.substring(start, end) + "/";
					start = end + 1;
					end = packName.indexOf(".", start);
				}
				path = path + packName.substring(start) + "/";
			}
		}
		// 调用ClassLoader的getResource方法，传入包含路径信息的类文件名
		java.net.URL url = loader.getResource(path + clsName);
		// 从URL对象中获取路径信息
		String realPath = url.getPath();
		// 去掉路径信息中的协议名"file:"
		int pos = realPath.indexOf("file:");
		if (pos > -1)
			realPath = realPath.substring(pos + 5);
		// 去掉路径信息最后包含类文件信息的部分，得到类所在的路径
		pos = realPath.indexOf(path + clsName);
		realPath = realPath.substring(0, pos - 1);
		// 如果类文件被打包到JAR等文件中时，去掉对应的JAR等打包文件名
		if (realPath.endsWith("!"))
			realPath = realPath.substring(0, realPath.lastIndexOf("/"));
		/*------------------------------------------------------------
		 ClassLoader的getResource方法使用了utf-8对路径信息进行了编码，当路径 
		  中存在中文和空格时，他会对这些字符进行转换，这样，得到的往往不是我们想要 
		  的真实路径，在此，调用了URLDecoder的decode方法进行解码，以便得到原始的 
		  中文及空格路径 
		-------------------------------------------------------------*/
		try {
			realPath = java.net.URLDecoder.decode(realPath, "utf-8");
		} catch (Exception e) {
			throw new RuntimeException(e); // NOPMD by dzqThinkpad on 16-4-1 下午4:33
		}
		org.jeecgframework.core.util.LogUtil.info("realPath----->"+realPath);
		return realPath;
	}
//	private static File getFile(String path){
//		File file = SendMail.class.getClassLoader().getResource("mailtemplate/test.ftl").getFile();
//		return file;
//	}
//

    public static void sendMailWithAttach(String toMailAddr, String subject,String filePath,String fileName,String copyPerson,String templatePath, Map<String, Object> map,SystemService systemService) {

        Configuration freeMarkerConfig = null;
        Template template = null;
		String htmlText = "";
        try {
            URL mainUrl = new URL(StaticValue.HTTP_HEADER+"/plug-in/login/images/mail-img-main.png");
            URL footerUrl = new URL(StaticValue.HTTP_HEADER+"/plug-in/login/images/mail-img-footer.jpg");
            URL logoUrl = new URL(StaticValue.HTTP_HEADER+"/plug-in/login/images/logo.png");

			freeMarkerConfig = new Configuration();
			freeMarkerConfig.setDirectoryForTemplateLoading(new File(getFilePath()));
			// 获取模板
			template = freeMarkerConfig.getTemplate(getFileName(templatePath),new Locale("Zh_cn"), "UTF-8");
			// 模板内容转换为string
			htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);

			if(StringUtil.isNotEmpty(copyPerson)){
				String persons[] = copyPerson.split(",");
				for (String person : persons) {

					HtmlEmail hemail1 = new HtmlEmail();
					String mainCid1 = hemail1.embed(mainUrl,"Main Img");
					String footerCid1 = hemail1.embed(footerUrl,"footer Img");
					String logoCid1 = hemail1.embed(logoUrl,"logo img");

					map.put("mainCid",mainCid1);
					map.put("footerCid",footerCid1);
					map.put("logoCid",logoCid1);

                    hemail1.setTLS(true);
					hemail1.setHostName(getHost(from));
					hemail1.setSmtpPort(getSmtpPort(from));
					hemail1.setCharset(charSet);
					hemail1.setFrom(from, fromName);
					hemail1.setAuthentication(username, password);
					hemail1.addTo(person);
					hemail1.setSubject(subject);
					hemail1.setHtmlMsg(htmlText);
					if(StringUtil.isNotEmpty(filePath)){
						File file = new File(filePath);
						EmailAttachment attachment = new EmailAttachment();
						attachment.setPath(file.getAbsolutePath());
						attachment.setDisposition(EmailAttachment.ATTACHMENT);
						attachment.setName(StringUtil.isNotEmpty(fileName)?fileName:file.getName());
						hemail1.attach(attachment);
					}

					hemail1.send();
					systemService.addLog("发送邮件,接收方："+toMailAddr+",内容为："+htmlText, Globals.log_type_SEND_EMAIL, Globals.Log_Leavel_INFO);

				}
			}

        } catch (Exception e) {
			systemService.addLog("发送邮件失败,接收方："+toMailAddr+",内容为："+htmlText, Globals.log_type_SEND_EMAIL, Globals.Log_Leavel_INFO);

			e.printStackTrace();
        }
    }
  
    /**
     * 微信提交订单后发送邮件给客户
     * @param toMailAddr 收件人
     * @param subject 标题
     * @param filePath 附件路径
     * @param fileName 附件名
     * @param templatePath 模板路径
     * @param map 参数
     * @param systemService
     * 2019年4月25日
     */
    public static void sendMailWithAttachForWXorder(String toMailAddr, String subject,String filePath,String fileName,String templatePath, Map<String, Object> map,SystemService systemService) {

        Configuration freeMarkerConfig = null;
        Template template = null;
		String htmlText = "";
        try {
			freeMarkerConfig = new Configuration();
			freeMarkerConfig.setDirectoryForTemplateLoading(new File(getFilePath()));
			// 获取模板
			template = freeMarkerConfig.getTemplate(getFileName(templatePath),new Locale("Zh_cn"), "UTF-8");
			

			if(StringUtil.isNotEmpty(toMailAddr)){
				String persons[] = toMailAddr.split(",");
				for (String person : persons) {
					HtmlEmail hemail1 = new HtmlEmail();
					// 模板内容转换为string
					if (StringUtil.isNotEmpty(map.get("logoCid"))) {
						String logoCid1 = hemail1.embed(map.get("logoCid").toString(),"logo img");
						map.put("logoCid",logoCid1);
					}
					htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
                    hemail1.setTLS(true);
					hemail1.setHostName(getHost(from));
					hemail1.setSmtpPort(getSmtpPort(from));
					hemail1.setCharset(charSet);
					hemail1.setFrom(from, fromName);
					hemail1.setAuthentication(username, password);
					hemail1.addTo(person);
					hemail1.setSubject(subject);
					hemail1.setHtmlMsg(htmlText);
					if(StringUtil.isNotEmpty(filePath)){
						File file = new File(filePath);
						EmailAttachment attachment = new EmailAttachment();
						attachment.setPath(file.getAbsolutePath());
						attachment.setDisposition(EmailAttachment.ATTACHMENT);
						attachment.setName(StringUtil.isNotEmpty(fileName)?fileName:file.getName());
						hemail1.attach(attachment);
					}

					hemail1.send();
					systemService.addLog("发送邮件,接收方："+person+",内容为："+htmlText, Globals.log_type_SEND_EMAIL, Globals.Log_Leavel_INFO);

				}
			}

        } catch (Exception e) {
			systemService.addLog("发送邮件失败,接收方："+toMailAddr+",内容为："+htmlText, Globals.log_type_SEND_EMAIL, Globals.Log_Leavel_INFO);

			e.printStackTrace();
        }
    }

  public static void main(String[] args)
  {
//	  ZyEmailEntity eMail = new ZyEmailEntity();
//	  eMail.setEmailSubject("巴可巡检任务分派通知");
//	  eMail.setEmailReceiver("1432919393@qq.com");
//	  Map<String, Object> paraMap = new HashMap<String, Object>();
//	  paraMap.put("engineerName", "王工");
//	  sendFtlMail(eMail, "barcoSendToTp.ftl", paraMap,null);
//	  SendMailUtil.sendeMail("1432919393@qq.com","测试","测试了");
	  //SendMailUtil.sendeMail("905085793@qq.com", "邮件说明", "邮件说明今天和明天多云转晴", systemService);


//      Map<String, Object> paraMap1 = new HashMap<String, Object>();
//      paraMap1.put("contacterName", "contacterName");
//      paraMap1.put("code", "123");
//      paraMap1.put("type", "1");
//      paraMap1.put("sn", "2");
//      paraMap1.put("description", "description");
//      paraMap1.put("level", "1");
//      paraMap1.put("authentication", "authentication1");
//      paraMap1.put("zyCinemaName", "zyCinemaName1");
//      paraMap1.put("zyContactsName", "zyContactsName1");
//      paraMap1.put("phone", "phone");
//      ZyEmailEntity eMail = new ZyEmailEntity();
//      eMail.setEmailSubject("测试");
//      eMail.setEmailReceiver("905085793@qq.com");
//      SendMailUtil.sendFtlMail(eMail, "mail_change_service.ftl", paraMap1, systemService);

  }

}